import React, { useState, useRef } from 'react';
import { Modal } from 'antd';
import Draggable from 'react-draggable';
import styles from './index.less';

export default ({ title, ...props }) => {
  const draggableRef = useRef(null);
  const [disabled, setDisabled] = useState(!REACT_APP_DRAGGABLE_MODAL);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });

  const handleStart = (_event, uiData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggableRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  return (
    <Modal
      {...props}
      destroyOnClose={REACT_APP_DRAGGABLE_MODAL_RESET}
      title={
        <div className={styles.draggableTitle}>
          {title}
          <div
            style={{ pointerEvents: REACT_APP_DRAGGABLE_MODAL ? 'auto' : 'none' }}
            className={styles.draggableTitleHandle}
            onMouseOver={() => {
              if (REACT_APP_DRAGGABLE_MODAL) {
                if (disabled) {
                  setDisabled(false);
                }
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
          />
        </div>
      }
      modalRender={(modal) => (
        <Draggable bounds={bounds} disabled={disabled} onStart={handleStart}>
          <div ref={draggableRef}>{modal}</div>
        </Draggable>
      )}
    />
  );
};
